/*
 * Copyright 2016-2018 TVI Go Easy.
 * Created on 2018/1/29 16:16
 */
package com.tvi.cloud.license.client;

import com.tvi.cloud.license.model.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.List;

/**
 * 通过 Spring Discovery client 调用 Organization 服务
 *
 * @author mechanic
 */
@Component
public class OrganizationDiscoveryClient {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    public Organization getOrganization(String id){
//        RestTemplate restTemplate = new RestTemplate();
        List<ServiceInstance> instances = discoveryClient.getInstances("organization-service");
        if (instances.size() == 0) {
            return null;
        }
        String serviceUri = MessageFormat.format("{0}/v1/organization/{1}",instances.get(0).getUri().toString(), id);

        serviceUri = "http://127.0.0.1:8030/api/org/v1/organization/1";
        System.out.println("!!!! SERVICE URI:  " + serviceUri);
        ResponseEntity<Organization> restExchange =
                restTemplate.exchange(
                        serviceUri,
                        HttpMethod.GET,
                        null, Organization.class, id);

        return restExchange.getBody();
    }
}
